/**
 * The database
 */
var dbShell;

/**
 * deviceready envent listener
 */
document.addEventListener("deviceready", function (){
	onDeviceReady();
}, false);

/**
 * onDeviceReady function
 */
function onDeviceReady(){
	dbShell = window.openDatabase("mainDB", "1","MoneyIODB",10000 );
}
/**
 * Document ready event
 */
$( document ).ready(function() {
	$('#doneBtn').bind('tapone',function(event, obj){
	        var addForm = $("form#addEntryForm");
	        if(addForm){
	            entry = new MoneyIOEntry("",addForm.find('input[name="inOut"]').val(), 
	                addForm.find('input[name="firstName"]').val(),
	                addForm.find('input[name="lastName"]').val(),
	                addForm.find('input[name="startDate"]').val(),
	                addForm.find('input[name="endDate"]').val(),
	                addForm.find('input[name="amount"]').val(),
	                addForm.find('input[name="unit"]').val(),
	                addForm.find('input[name="comment"]').val());     
	            if(validateNewEntry(entry)){
	                addNewEntry(entry);
	            }
	            else{
	            	
	            	event.preventDefault();
	            }
	        };
	    });
});


function validateNewEntry(entry){
    if(!entry){
        return false;
    }
    else{
        if(!entry.inOut || !entry.firstName || !entry.startDate || !entry.amount){
            alert("Les champs Entree/Sortie, Prenom, Date d'emprunt et Montant sont obligatoires.");
            return false;
        }
        if(entry.amount && parseInt(entry.amount) < 0){
        	alert("Le montant doit etre positif.");
            return false;
        }
        
        return true;
    }
}

function addNewEntry(entry){
    if(entry){
    	saveEntry(entry);
    }
}

/**
 * Function for saving an entry in the database
 * @param entry
 */
function saveEntry(entry){
	request = 'INSERT INTO INOUT (kind,firstname,lastname,amount,unit,startDate,endDate,comment) '
		+'VALUES ("'+entry.inOut+'","'+entry.firstName+'","'+entry.lastName+'","'+entry.amount+'","'+entry.unit+'","'+entry.startDate+'","'+entry.endDate+'","'+entry.comment+'")';
	dbShell.transaction(function(tx){
		tx.executeSql(request);
		
	});
}
